#coding=utf-8

from Model.MZCCMulLineRuleItem import *
from Model.MZCCMulLineRuleBufferItem import *
from Model.MZCCProblemItem import *
from Config.MZCCSpecialRuleHeader import *

from MZCCCheckerSupport import *

'''
' 多行处理Buffer池
'  key : 某个规则项的Id
'  value : 规则项buffer
'''
global mzccMulRuleBufferPool
mzccMulRuleBufferPool = {};

'''
' 多行规则检查
' 输入：
'  ruleItem : 规则项
'  curLineNum : 当前行号
'  curNspLine : 当前无空格行
'  lastNspLine : 上一个无空格行
'  curLine : 当前行
'  lineContext : 当前行检查上下文
' 输出：
'  问题项（MZCCProblemItem, 0或1个）
'''
def mzccMulRuleCheck(ruleItem, lineContext):

	# 获取buffer
	tmpBuffer = mzccMulRuleBuffer(ruleItem.ruleId);

	tmpProblem = None;
	if tmpBuffer.isBufferEmpty():
		#规则未开始逻辑
		results = mzccRegex(lineContext.curNspLine, ruleItem.startRe);
		if len(results) != 0:
			tmpBuffer.lineNum = lineContext.curLineNum;
			tmpBuffer.bufferStr += lineContext.lastNspLine;
			tmpBuffer.bufferStr += lineContext.curNspLine;
	else:
		if 0 == len(ruleItem.udCheckFuncName):
			tmpBuffer.bufferStr += lineContext.curNspLine;

	if 0 == tmpBuffer.isBufferEmpty():

		#规则进行中逻辑
		results = mzccRegex(lineContext.curNspLine, ruleItem.lineRecordRe);
		if len(results) != 0:
			tmpBuffer.lineNum = lineContext.curLineNum;

		checkResult = 0;
		if 0 != len(ruleItem.udCheckFuncName):
			checkResult = eval(ruleItem.udCheckFuncName)(tmpBuffer, lineContext);
		else:
			checkResult = mzccMulRuleNormalCheck(ruleItem, lineContext.curLineNum, tmpBuffer.bufferStr);

		# 处理检测结果
		tmpProblem = mzccHandleMulRuleCheckResult(ruleItem, tmpBuffer, checkResult);

	return tmpProblem;


########################################################################
# 支持函数

'''
' 通过规则Id获取规则Buffer
' 注：
'  若buffer池中不存在期望获取的buffer，
'  则创建一个buffer项并返回
'''
def mzccMulRuleBuffer(bufferKey):
    if mzccMulRuleBufferPool.has_key(bufferKey) == False:
        mzccMulRuleBufferPool[bufferKey] = MZCCMulLineRuleBufferItem();
    return mzccMulRuleBufferPool[bufferKey];

def mzccMulRuleBufferClear():
	global mzccMulRuleBufferPool;
	mzccMulRuleBufferPool = {};

'''
' 默认方式检测
'  ruleItem : 规则项
'  curLineNum : 当前行号
'  checkStr : 检测内容（无空格换行）
' 返回值：
'  0 通过；1 拒绝；2 待定
'''
def mzccMulRuleNormalCheck(ruleItem, curLineNum, checkStr):
	acceptResult = mzccRegex(checkStr, ruleItem.acceptRe);
	if len(acceptResult) != 0:
		return 0;
	rejectResult = mzccRegex(checkStr, ruleItem.rejectRe);
	if len(rejectResult) != 0:
		return 1;
	return 2;

'''
' 针对检查结果进行缓存的操作处理，并给出问题
'  ruleItem : 规则项
'  checkBuffer : 检查buffer
'  checkResult : 判定值（0 通过；1 拒绝；2 待定）
' 返回值：
'  问题项（MZCCProblemItem, 0或1个）
'''
def mzccHandleMulRuleCheckResult(ruleItem, checkBuffer, checkResult):
	if 2 == checkResult:
		return None;
	tmpProblem = None;
	if 1 == checkResult:
		tmpProblem = MZCCProblemItem();
		tmpProblem.lineNum = checkBuffer.lineNum;
		tmpProblem.desc = ruleItem.desc;
		tmpProblem.ruleId = ruleItem.ruleId;
	#0、1都需要清空buffer
	checkBuffer.bufferStr = "";
	return tmpProblem;


